package com.ygp.lock.rlock;

import com.ygp.utils.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <Description> <br>
 *
 * @author linmiaolai@sanyygp.com<br>
 * @version 1.0<br>
 * @date 2021/11/16 <br>
 */
@Slf4j(topic = "c.InterruptedTest")
public class LockOverTime {
    ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        new LockOverTime().method2();
    }

    public void method1() {
        Thread t1 = new Thread(() -> {
            log.debug("启动。。。");
            if (lock.tryLock()) {
                try {
                    log.debug("获得了锁");
                } finally {
                    lock.unlock();
                }
            } else {
                log.debug("获取立刻失败，返回");
            }
        }, "t1");

        lock.lock();
        log.debug("获得了锁");
        t1.start();
        try {
            Sleeper.sleep(2);
        } finally {
            lock.unlock();
        }
    }

    public void method2() {
        Thread t1 = new Thread(() -> {
            log.debug("启动。。。");
            try {
                if (!lock.tryLock(1, TimeUnit.SECONDS)) {
                    log.debug("获取等待 1s 后失败，返回");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                log.debug("获得了锁");
            } finally {
                lock.unlock();
            }
        }, "t1");

        lock.lock();
        log.debug("获得了锁");
        t1.start();
        try {
            Sleeper.sleep(2);
        } finally {
            lock.unlock();
        }
    }
}
